package com.gfilechooser;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author Guillermo
 */

public class FileListAdapter extends BaseAdapter {

	private final static int ICON_FOLDER = R.drawable.ic_folder;
	private final static int ICON_FILE = R.drawable.ic_file;

	private List<File> files = new ArrayList<File>();
	private LayoutInflater inflater;

	public FileListAdapter(Context context) {
		inflater = LayoutInflater.from(context);
	}

	public ArrayList<File> getListItems() {
		return (ArrayList<File>) files;
	}

	public void setListItems(List<File> files) {
		this.files = files;
		notifyDataSetChanged();
	}

	public int getCount() {
		return files.size();
	}

	public void add(File file) {
		files.add(file);
	}

	public void clear() {
		files.clear();
	}

	public Object getItem(int position) {
		return files.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ViewHolder holder = null;
		if (row == null) {
			row = inflater.inflate(R.layout.activity_file, parent, false);
			holder = new ViewHolder(row);
			row.setTag(holder);
		} else {
			holder = (ViewHolder) row.getTag();
		}
		final File file = (File) getItem(position);
		holder.nameView.setText(file.getName());
		holder.iconView.setImageResource(file.isDirectory() ? ICON_FOLDER
				: ICON_FILE);
		return row;
	}

	static class ViewHolder {
		TextView nameView;
		ImageView iconView;
		ViewHolder(View row) {
			nameView = (TextView) row.findViewById(R.id.file_name);
			iconView = (ImageView) row.findViewById(R.id.file_icon);
		}
	}
}